package team.southcat.wsyygh.hospital.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import team.southcat.wsyygh.common.exception.WsyyghException;
import team.southcat.wsyygh.common.result.Result;
import team.southcat.wsyygh.common.result.ResultCodeEnum;
import team.southcat.wsyygh.hospital.mapper.ScheduleMapper;
import team.southcat.wsyygh.hospital.service.DepartmentService;
import team.southcat.wsyygh.hospital.service.DoctorService;
import team.southcat.wsyygh.hospital.service.HospitalService;
import team.southcat.wsyygh.hospital.service.ScheduleService;
import team.southcat.wsyygh.model.pojo.hospital.*;
import team.southcat.wsyygh.model.pojo.order.ScheduleOrderVo;
import team.southcat.wsyygh.model.pojo.user.Admin;
import team.southcat.wsyygh.user.client.AdminFeignClient;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author QiuSiYi
 * @since 2023-04-20
 */
@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, Schedule> implements ScheduleService {

    @Autowired
    private HospitalService hospitalService;

    @Resource
    private DoctorService doctorService;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private ScheduleService scheduleService;

    @Autowired
    private AdminFeignClient adminFeignClient;

    /**
     * 分页查询医生排班信息
     *
     * @param page       页数
     * @param limit      条数
     * @param scheduleVo 查询条件
     * @return
     */
    @Override
    public Page getSchedulePageList(int page, int limit, ScheduleVo scheduleVo) {
        //分页构造器,传入页码和大小
        Page<Schedule> pageInfo = new Page<>(page, limit);

        //根据传递过来的医生名称模糊查询得出的医生Id集合
        List<Long> doctorIdsByName = new ArrayList<>();
        //根据传递过来的科室Id查询出来所属医生的Id集合
        List<Long> doctorIdsByDepartment = new ArrayList<>();

        //最终筛选上面两个集合都在的医生Id
        List<Long> doctorIds = new ArrayList<>();

        //标记有无查询条件
        boolean flagName = false;
        boolean flagDepartment = false;

        //如果传递过来的科室Id存在，查询出属于该科室的医生集合
        if (scheduleVo.getDepartmentId() != null) {
            flagDepartment = true;
            LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(Doctor::getDepartmentId, scheduleVo.getDepartmentId());
            List<Doctor> doctors = doctorService.list(queryWrapper);
            for (Doctor doctor : doctors) {
                if (doctor.getId() != null) {
                    doctorIdsByDepartment.add(doctor.getId());
                }
            }
        }

        //如果传递过来的医生名称存在,模糊查询出医生集合
        if (scheduleVo.getDoctorName() != null) {
            flagName = true;
            LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(Doctor::getDoctorName, scheduleVo.getDoctorName());
            List<Doctor> doctors = doctorService.list(queryWrapper);
            for (Doctor doctor : doctors) {
                if (doctor.getId() != null) {
                    doctorIdsByName.add(doctor.getId());
                }
            }
        }


        //条件构造器
        LambdaQueryWrapper<Schedule> queryWrapper = new LambdaQueryWrapper<>();

        //添加查询条件
        //安排时间
        queryWrapper.eq(scheduleVo.getWorkTime() != null, Schedule::getWorkTime, scheduleVo.getWorkTime());
        //选择日期
        queryWrapper.eq(scheduleVo.getWorkDate() != null, Schedule::getWorkDate, scheduleVo.getWorkDate());

        //根据创建时间排序
        queryWrapper.orderByDesc(Schedule::getUpdateTime);

        queryWrapper.eq(Schedule::getHospitalId, scheduleVo.getHospitalId());

        if (flagDepartment) {
            //如果两个集合都存在
            if (flagName) {
                //查询出两个集合都存在的医生Id
                for (Long doctorId : doctorIdsByName) {
                    for (Long doctor2Id : doctorIdsByDepartment) {
                        if (doctor2Id == doctorId) {
                            doctorIds.add(doctorId);
                            break;
                        }
                    }
                }
            } else {
                //只有科室的查询条件
                doctorIds.addAll(doctorIdsByDepartment);
            }
        } else {
            //只有名称的查询条件
            if (flagName) {
                doctorIds.addAll(doctorIdsByName);
            }
        }

        //有该查询条件才执行
        if (flagDepartment || flagName) {
            //放置到queryWrapper中，因为and优先级比or高，所以用该方式
            if (doctorIds.size() > 0) {
                queryWrapper.and(wq -> {
                    for (int i = 0; i < doctorIds.size(); i++) {
                        if (i == 0) {
                            wq.eq(Schedule::getDoctorId, doctorIds.get(i));
                        } else {
                            wq.or().eq(Schedule::getDoctorId, doctorIds.get(i));
                        }
                    }
                });
            } else {
                //选择的科室没有医生
                queryWrapper.eq(Schedule::getDoctorId, 0);
            }
        }


        //执行查询
        this.page(pageInfo, queryWrapper);

        //对象拷贝为Vo对象Page
        Page<ScheduleVo> voPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, voPage);

        //取出数据并赋值转换
        List<Schedule> records = pageInfo.getRecords();

        //使用流转换,遍历将医生id改为医生名字
        List<ScheduleVo> scheduleVos = records.stream().map((schedule) -> {
            ScheduleVo scheduleVo1 = new ScheduleVo();
            BeanUtils.copyProperties(schedule, scheduleVo1);

            //若剩余预约量为0,不可约
            if (schedule.getBookingSurplus() == 0) {
                scheduleVo1.setStatus(0);
            }

            //将安排时间转为中文展示
            if (schedule.getWorkTime() == 1) {
                scheduleVo1.setTime("下午");
            } else if (schedule.getWorkTime() == 0) {
                scheduleVo1.setTime("上午");
            }

            //根据医生ID查询出医生数据,并存储医生名字
            Doctor doctor = doctorService.getById(schedule.getDoctorId());
            scheduleVo1.setDoctorName(doctor.getDoctorName());

            //根据医生所属科室id查询出科室，并存储科室名称
            Department department = departmentService.getById(doctor.getDepartmentId());
            scheduleVo1.setDepartmentName(department.getDepartmentName());

            return scheduleVo1;
        }).collect(Collectors.toList());

        //放数据，返回
        voPage.setRecords(scheduleVos);
        return voPage;
    }

    /**
     * 新增医生排班信息
     *
     * @param schedule 医生排班信息
     * @return 返回成功失败
     */
    @Override
    @Transactional
    public Result addSchedule(ScheduleVo schedule, String adminId) {
        if (schedule.getBookingCount() == null) {
            return Result.fail().message("总预约数不能为空");
        }
        if (schedule.getBookingCount() <= 0) {
            return Result.fail().message("总预约数不能小于1");
        } else if (schedule.getBookingCount() > 40) {
            return Result.fail().message("总预约数不能大于40");
        }
        if (schedule.getDoctorId() == null) {
            return Result.fail().message("必须选医生！！！");
        }
        if (schedule.getWorkTime() == null) {
            return Result.fail().message("必须选时间！！！");
        }
        if (schedule.getAmount() == null) {
            schedule.setAmount(BigDecimal.valueOf(0));
        }
        Schedule schedule1 = new Schedule();
        BeanUtils.copyProperties(schedule, schedule1);

        List<Date> workDateList = schedule.getWorkDateList();
        Date d1 = workDateList.get(0);
        Date d2 = workDateList.get(1);
        Date tmp = d1;
        Calendar dd = Calendar.getInstance();
        dd.setTime(d1);
        //日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            while (tmp.getTime() <= d2.getTime()) {
                boolean flag = boolScheduleByDate(schedule1, tmp);
                if (!flag) {
                    throw new Exception("该医生在" + sdf.format(tmp) + "的这个时间段已有排班安排");
                }
                //天数加上1
                dd.add(Calendar.DAY_OF_MONTH, 1);
                tmp = dd.getTime();
            }
        } catch (Exception e) {
            return Result.fail().message(e.getMessage());
        }

        schedule1.setBookingSurplus(schedule1.getBookingCount());
        Date date;
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.now();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        date = Date.from(zdt.toInstant());
        schedule1.setCreateTime(date);
        schedule1.setUpdateTime(date);
        schedule1.setHospitalId(getAdmin(adminId).getHospitalId());
        //将状态设为可预约
        schedule1.setStatus(1);
        tmp = d1;
        dd.setTime(d1);
        while (tmp.getTime() <= d2.getTime()) {
            schedule1.setWorkDate(tmp);
            schedule1.setId(null);
            int insert = baseMapper.insert(schedule1);
            //天数加上1
            dd.add(Calendar.DAY_OF_MONTH, 1);
            tmp = dd.getTime();
        }
        return Result.ok();
    }

    private boolean boolScheduleByDate(Schedule schedule1, Date tmp) {
        schedule1.setWorkDate(tmp);

        //判断该医生在该日期的该时间有无记录
        LambdaQueryWrapper<Schedule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Schedule::getDoctorId, schedule1.getDoctorId());
        queryWrapper.eq(Schedule::getWorkDate, schedule1.getWorkDate());
        queryWrapper.eq(Schedule::getWorkTime, schedule1.getWorkTime());

        List<Schedule> schedules = baseMapper.selectList(queryWrapper);
        if (schedules.size() > 0) {
            // return Result.fail().message("该医生在该日期的这个时间段已有排班安排");
            return false;
        }
        return true;
    }

    /**
     * 根据id查询医生排班信息
     *
     * @param id 医生排班信息Id
     * @return 结果
     */
    @Override
    public Result getScheduleById(Integer id) {
        //查询出医生排班安排信息
        Schedule schedule = baseMapper.selectById(id);
        ScheduleVo scheduleVo = switchVo(schedule);
        return Result.ok(scheduleVo);
    }

    private ScheduleVo switchVo(Schedule schedule) {
        if (schedule != null){
            ScheduleVo scheduleVo = new ScheduleVo();
            BeanUtils.copyProperties(schedule, scheduleVo);

            scheduleVo.setHospitalName(hospitalService.getById(schedule.getHospitalId()).getHospitalName());
            //查询出该医生的信息
            Doctor doctor = doctorService.getById(schedule.getDoctorId());
            scheduleVo.setDoctorName(doctor.getDoctorName());
            scheduleVo.setTitle(doctor.getTitle());
            scheduleVo.setSkill(doctor.getSkill());
            scheduleVo.setDoctor(doctor);

            //查询出该医生的科室信息
            Department department = departmentService.getById(doctor.getDepartmentId());

            //将科室id和该科室父Id存进Vo
            scheduleVo.setDepartmentId(department.getId());
            scheduleVo.setDepartmentParentId(department.getParentId());
            scheduleVo.setDepartmentName(department.getDepartmentName());

            String dayOfWeek = this.getDayOfWeek(new DateTime(schedule.getWorkDate()));
            scheduleVo.setDayOfWeek(dayOfWeek);
            return scheduleVo;
        }

        return null;
    }

    /**
     * 修改医生排班信息
     *
     * @param schedule 医生排班信息
     * @return 结果
     */
    @Override
    public Result updateSchedule(Schedule schedule) {
        Schedule schedule1 = baseMapper.selectById(schedule.getId());
        int num = schedule1.getBookingCount() - schedule1.getBookingSurplus();
        if (schedule.getBookingCount() <= 0) {
            return Result.fail().message("总预约数不能小于1");
        } else if (schedule.getBookingCount() > 40) {
            return Result.fail().message("总预约数不能大于40");
        }
        if (schedule.getBookingCount() - num < 0) {
            return Result.fail().message("该医生排班已经预约数超过总预约数，无法更改!");
        }

        //当医生和日期和时间没被修改则不用判断
        if (!Objects.equals(schedule.getDoctorId(), schedule1.getDoctorId()) || !Objects.equals(schedule.getWorkDate(), schedule1.getWorkDate()) ||
                !Objects.equals(schedule.getWorkTime(), schedule1.getWorkTime())) {
            //判断该医生在该日期的该时间有无记录
            LambdaQueryWrapper<Schedule> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Schedule::getDoctorId, schedule.getDoctorId());
            queryWrapper.eq(Schedule::getWorkDate, schedule.getWorkDate());
            queryWrapper.eq(Schedule::getWorkTime, schedule.getWorkTime());

            List<Schedule> schedules = baseMapper.selectList(queryWrapper);
            if (schedules.size() > 0) {
                return Result.fail().message("该医生在该日期的这个时间段已有排班安排");
            }
        }

        //若之前有预约，减去该预约
        schedule.setBookingSurplus(schedule.getBookingCount() - num);
        //修改更新时间
        Date date;
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.now();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        date = Date.from(zdt.toInstant());
        schedule.setUpdateTime(date);
        int flag = baseMapper.updateById(schedule);
        return flag > 0 ? Result.ok() : Result.fail().message("更新失败！");
    }

    public List<Schedule> getScheduleByDoctorIds(List<Long> doctorIds) {
        LambdaQueryWrapper<Schedule> queryWrapper = new LambdaQueryWrapper<>();
        if (doctorIds.size() > 0) {
            //放置到queryWrapper中，因为and优先级比or高，所以用该方式
            queryWrapper.and(wq -> {
                for (int i = 0; i < doctorIds.size(); i++) {
                    if (i == 0) {
                        wq.eq(Schedule::getDoctorId, doctorIds.get(i));
                    } else {
                        wq.or().eq(Schedule::getDoctorId, doctorIds.get(i));
                    }
                }
            });
        } else {
            //选择的科室没有医生
            queryWrapper.eq(Schedule::getDoctorId, 0);
        }
        List<Schedule> schedules = scheduleService.list(queryWrapper);
        return schedules;
    }

    //获取预约挂号界面时间选项数据
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hospitalId, String departmentId) {
        //获取医院信息，需要预约规则信息
        Hospital hospital = hospitalService.getById(hospitalId);

        //1.根据医院预约规则信息获取可预约的时间List
        IPage<Date> iPage = this.getDateList(page, limit, hospital);
        List<Date> dateList = iPage.getRecords();

        //2.
        List<BookingScheduleRuleVo> scheduleVoList = baseMapper.selectBookingScheduleRuleVo(departmentId);

        //合并数据  map集合 key：日期  value：预约规则和剩余数量等
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }

        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for(int i=0, len=dateList.size(); i<len; i++) {
            Date date = dateList.get(i);
            //从map集合中根据key日期获取value值
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if(bookingScheduleRuleVo == null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }

            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期对应的星期
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == len-1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && page == 1) {
                DateTime stopTime = this.swtichDateTime(new Date(), new DateTime(hospital.getBookingruleStoptime()).toString("HH:mm"));
                if(stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        Map<String,Object> result = new HashMap<>();
        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getById(hospitalId).getHospitalName());
        //科室
        Department department = departmentService.getById(departmentId);
        //大科室名称
        baseMap.put("bigname", departmentService.getById(department.getParentId()).getDepartmentName());
        //科室名称
        baseMap.put("depname", department.getDepartmentName());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", new DateTime(hospital.getBookingruleReleasetime()).toString("HH:mm"));
        //停号时间
        baseMap.put("stopTime", new DateTime(hospital.getBookingruleStoptime()).toString("HH:mm"));
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * 获取当天的预约数据
     * @param hoscode
     * @param depcode
     * @param workDate
     * @return
     */
    @Override
    public List<ScheduleVo> getDetailSchedule(String hoscode, String depcode, String workDate) {
        LambdaQueryWrapper<Schedule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Schedule::getHospitalId, hoscode);
        List<Doctor> doctors = doctorService.getDoctorsByDepartmentId(depcode);
        List<String> list = doctors.stream().map(item -> {
            String id = String.valueOf(item.getId());
            return id;
        }).collect(Collectors.toList());
        queryWrapper.in(Schedule::getDoctorId, list);
        queryWrapper.eq(Schedule::getWorkDate, workDate);

        List<Schedule> schedules = baseMapper.selectList(queryWrapper);

        List<ScheduleVo> scheduleVos = schedules.stream().map(item -> {
            Long hospitalId = item.getHospitalId();
            Doctor doctor = doctorService.getById(hospitalId);

            ScheduleVo scheduleVo = new ScheduleVo();
            BeanUtils.copyProperties(item, scheduleVo);
            scheduleVo.setDoctor(doctor);

            return scheduleVo;
        }).collect(Collectors.toList());


        return scheduleVos;
    }

    @Override
    public ScheduleVo getByScheduleId(String scheduleId) {
        Schedule schedule = baseMapper.selectById(scheduleId);
        ScheduleVo scheduleVo = this.switchVo(schedule);
        return scheduleVo;
    }

    /**
     * 根据医院预约规则信息获取可预约的时间List
     * @param page
     * @param limit
     * @param hospital
     * @return
     */
    private IPage<Date> getDateList(Integer page, Integer limit, Hospital hospital) {
        DateTime releasetime = this.swtichDateTime(new Date(), new DateTime(hospital.getBookingruleReleasetime()).toString("HH:mm"));
        Integer cycle = hospital.getBookingruleCycle();
        //如果当天放号时间已过，预约周期从后一天开始计算，周期+1
        if (releasetime.isBeforeNow()) {
            cycle += 1;
        }

        //获取可预约所有日期，最后一天显示即将放号
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }

        //因为预约周期不同，每页最多显示7天，预约周期大于7天的要进行分页
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        //如果预约周期<=7,直接显示
        if (dateList.size() < end) {
            end = dateList.size();
        }
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new Page<Date>(page, 7, dateList.size());
        iPage.setRecords(pageDateList);

        return iPage;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     *
     * @param date
     * @param timeString
     * @return
     */
    private DateTime swtichDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //获取排班数据
        Schedule schedule = baseMapper.selectById(scheduleId);
        if (schedule == null){
            throw new WsyyghException(ResultCodeEnum.PARAM_ERROR);
        }

        //获取医院的预约挂号规则
        HospitalVo hospitalVo = hospitalService.selectById(schedule.getHospitalId());
        if (hospitalVo == null){
            throw new WsyyghException(ResultCodeEnum.PARAM_ERROR);
        }

        //设置数据
        scheduleOrderVo.setHospitalId(String.valueOf(schedule.getHospitalId()));
        scheduleOrderVo.setHospitalName(hospitalVo.getHospitalName());
        Doctor doctor = doctorService.getById(schedule.getDoctorId());
        Department department = departmentService.getById(doctor.getDepartmentId());
        scheduleOrderVo.setDepartmentId(String.valueOf(department.getId()));
        scheduleOrderVo.setDepartmentName(department.getDepartmentName());
        scheduleOrderVo.setScheduleId(String.valueOf(schedule.getId()));
        scheduleOrderVo.setBookingSurplus(schedule.getBookingSurplus());
        scheduleOrderVo.setTitle(doctor.getTitle());
        scheduleOrderVo.setWorkDate(schedule.getWorkDate());
        scheduleOrderVo.setWorkTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截至天数
        int quitday = hospitalVo.getBookingruleQuitday();
        DateTime quit = this.swtichDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitday).toDate(),
                new DateTime(hospitalVo.getBookingruleQuittime()).toString("HH:mm"));
        scheduleOrderVo.setQuitTime(quit.toDate());

        //预约开始时间 当天的workDate - 预约周期cycle + 当天放号时间bookingruleReleasetime
        // 6-16 开始时间为 6-16 - 10 = 6.6 08:30
        DateTime startTime = this.swtichDateTime(new DateTime(schedule.getWorkDate()).minusDays(hospitalVo.getBookingruleCycle()).toDate(),
                new DateTime(hospitalVo.getBookingruleReleasetime()).toString("HH:mm"));
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截至时间
        DateTime endTime = this.swtichDateTime(new DateTime(schedule.getWorkDate()).toDate(), new DateTime(hospitalVo.getBookingruleStoptime()).toString("HH:mm"));
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.swtichDateTime(new Date(), new DateTime(hospitalVo.getBookingruleStoptime()).toString("HH:mm"));
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    @Override
    public void update(Schedule schedule) {
        baseMapper.updateById(schedule);
    }

    private Admin getAdmin(String adminId) {
        Object adminObj = adminFeignClient.getAdminById(Integer.valueOf(adminId)).getData();
        return JSONObject.parseObject(JSON.toJSONString(adminObj), Admin.class);
    }

}
